package com.fqcar.fqdf.ui;

import android.content.Intent;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.Response;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.fqcar.fqdf.DFApp;
import com.fqcar.fqdf.R;
import com.fqcar.fqdf.entity.CarDetailEntity;
import com.fqcar.fqdf.entity.CarDetailRespBean;
import com.fqcar.fqdf.entity.CarInfo;
import com.fqcar.fqdf.entity.CarListReqBean;
import com.fqcar.fqdf.entity.CarListRespBean;
import com.fqcar.fqdf.entity.CityEntity;
import com.fqcar.fqdf.entity.UnFinishDealRespBean;
import com.fqcar.fqdf.entity.UseableStationRespBean;
import com.fqcar.fqdf.service.RequestOptService;
import com.fqcar.fqdf.ui.main.MainDialogHelper;
import com.fqcar.fqdf.ui.main.holder.MainHolderHelper;
import com.fqcar.fqdf.ui.main.marker.MainBaiduMarkerHelper;
import com.fqcar.fqdf.ui.main.runnable.BaiduRunnable;
import com.fqcar.fqdf.ui.main.runnable.noui.CarOverlayRunnable;
import com.fqcar.fqdf.ui.main.runnable.ui.UpdateCityTitleRunnable;
import com.fqcar.fqdf.ui.main.view.MainViewHelper;
import com.fqcar.fqdf.util.Constants;
import com.fqcar.fqdf.util.DFUpdate;
import com.fqcar.fqdf.util.NavigationUtils;
import com.fqcar.fqdf.util.ReqConstants;
import com.fqcar.fqdf.util.SharedPreferenceUtil;
import com.fqcar.fqdf.util.SkipUtil;
import com.fqcar.fqdf.view.MapOverlayHelper;
import com.fqdf.framework.android.net.response.NetBeanWrapper;
import com.fqdf.framework.android.util.AndroidUtils;
import com.fqdf.framework.android.util.CheckLogicUtil;
import com.fqdf.framework.android.util.DialogUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lvsidong
 *
 */
public class NormalHomeActivity extends MapLocationActivity implements BaiduMap.OnMapStatusChangeListener,
        BaiduMap.OnMarkerClickListener, BaiduMap.OnMapClickListener, OnGetGeoCoderResultListener {

    @BindView(R.id.baidumap)
    MapView baidumapView;

    //用户选择的城市
    private CityEntity userCityEntity;
    // 首页网点数据结果
    private CarListRespBean carListRespBean;
    // 首页电子围栏
    private UseableStationRespBean useableStationRespBean;
    // 首页的dialog的帮助类
    private MainDialogHelper dialogHelper;
    // 首页百度地图绘制overlay的帮助类
    private MainBaiduMarkerHelper markerHelper;
    // 首页控制view显示隐藏以及更新内容的帮助类
    private MainViewHelper mainViewHelper;
    // 首页用来绘制overlay创建view转化的帮助类
    private MainHolderHelper mainHolderHelper;

    // 路径规划的overlay，保存的最近一次路径规划对象
//    private WalkingRouteOverlay lastWalkingRouteOverlay;
    // 用来判断是否是首次进行路径规划绘制，如果是首次的话会进行适应屏幕进行显示
//    private boolean firstWalkRouter = true;
    // 用来保存最后一次用户点击的overlay对象
    private Marker lastClickMarker;

    // 搜索模块，也可去掉地图模块独立使用
//    private RoutePlanSearch routerSearch;
    // 当前选择的取车网点的数据对象
    private CarInfo curSelCarEntity;
    //当前选取车辆的详情
    private CarDetailEntity carDetailEntity;
    private CarDetailRespBean carDetailRespBean;
    // 当前选择的还车网点的数据对象
//    private ParkingEntity curSelReturnParkingEntity;
    // 用来进行定时刷新的runnable对象
//    private TimeIntervalRefreshRunnable curFreshRunnable = new TimeIntervalRefreshRunnable();
    // 进行自动刷新数据的时间间隔
//    private static final int TIME_INTERVAL_REFRESH = 10 * 60 * 1000;

    private BDLocation location = null;
    private GeoCoder geoCoder;
    protected CarListReqBean carListReqBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        ButterKnife.bind(this);
        //初始化数据
        initData();
        // 调用父类的地图初始化
        initMap(baidumapView);
        // 初始化本地地图的个性设置
        initMyMap();
        // 初始化各个帮助类
        initHelper();
        // 初始化请求数据
//        initReqData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        // 判断当前用户是否进行登录
        if (!CheckLogicUtil.isEmpty(SharedPreferenceUtil.getStringSPAttrs(NormalHomeActivity.this, SharedPreferenceUtil.AttrInfo.USER_TOKEN, ""))) {
            // 获取订单状态
            getCurrentOrderForInit();
        }
    }

    // 初始化地图设置
    private void initMyMap() {
        mBaiduMap.setOnMarkerClickListener(this);
        mBaiduMap.setOnMapStatusChangeListener(this);
        mBaiduMap.setOnMapClickListener(this);
//        routerSearch = RoutePlanSearch.newInstance();
//        routerSearch.setOnGetRoutePlanResultListener(this);

    }

    // 初始化帮助类
    private void initHelper() {
        dialogHelper = new MainDialogHelper();
        mainHolderHelper = new MainHolderHelper(this);
        markerHelper = new MainBaiduMarkerHelper(this, mBaiduMap, mainHolderHelper);
        mainViewHelper = new MainViewHelper(this, getWindow().findViewById(android.R.id.content));
    }

    private void initData() {
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(this);
        carListReqBean = new CarListReqBean();

    }

    /**
     * 初始化请求数据
     */
    private void initReqData() {
        // 先进行app更新，保持老的逻辑
        new DFUpdate(this).requestUpdate();

        // 开始进行定位
        startLocationUpdate();

        // 根据定位获取网点数据以及更新对应的城市代码。如果定位数据为空，则进行1秒等待后继续调用
        getThreadHandler().post(new Runnable() {
            @Override
            public void run() {
                if (getCurValidAndCityLocation() != null) {

                    // 判断当前用户是否进行登录
                    if (!CheckLogicUtil.isEmpty(SharedPreferenceUtil.getStringSPAttrs(NormalHomeActivity.this, SharedPreferenceUtil.AttrInfo.USER_TOKEN, ""))) {
                        // 获取订单状态
                        getCurrentOrderForInit();
                    }
//                    setOpenUserLocation(true);
                    location = getCurValidAndCityLocation();
//                    Log.d("区县信息：",location.getDistrict());
//                    updateData(location.getLongitude(), location.getLatitude(), location.getCityCode());
                    updateData();
//                    getUseableStation();
                    MapStatus mMapStatus = new MapStatus.Builder()
                            .target(new LatLng(location.getLatitude(), location.getLongitude()))
                            .zoom(MAP_ZOOM_DEFAULT)
                            .build();
                    //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                    MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                    //改变地图状态
                    mBaiduMap.animateMapStatus(mMapStatusUpdate);

                    getUiHandler().post(new UpdateCityTitleRunnable(mainViewHelper, location.getCity()));

                } else {
                    startLocationUpdate();
                    getThreadHandler().postDelayed(this, 1000);
                }
            }
        });
    }

    /**
     * 开启定时刷新功能
     */
//    private void startFreshRunnable() {
//        getUiHandler().postDelayed(curFreshRunnable, TIME_INTERVAL_REFRESH);
//    }

    /**
     * 关闭定时刷新功能
     */
//    private void stopFreshRunnable() {
//        getUiHandler().removeCallbacks(curFreshRunnable);
//    }
    @Override
    protected void onResume() {
        super.onResume();
        initReqData();
//        startFreshRunnable();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        stopFreshRunnable();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 处理原有逻辑，主要处理退出以及不同界面返回主界面后进行刷新数据
        if (null != intent.getAction() && intent.getAction().toString().equals(Constants.Action.EXIT_ACTION)) {
            SkipUtil.exitAPP(this);
        } else if (null != intent.getAction() && intent.getAction().toString().equals(Constants.Action.HOME_REFRESH_ACTION)) {
            doRefreshMap();
        } else if (null != intent.getAction() && intent.getAction().toString().equals(Constants.Action.HOME_SELECT_CONDITION_ACTION)) {
            if (intent.getParcelableExtra(Constants.BUNDLE_DATA) != null) {
                userCityEntity = intent.getParcelableExtra(Constants.BUNDLE_DATA);
//                Constants.userCityCode = userCityEntity.getCityCode();
                mainViewHelper.updateCityName(userCityEntity.getName());
            }
            if (intent.getParcelableExtra(Constants.BUNDLE_DATA_EXT) != null) {
                carListReqBean = new CarListReqBean();
                carListReqBean = intent.getParcelableExtra(Constants.BUNDLE_DATA_EXT);
            }

            clearClickInfo();

            changePosition(userCityEntity == null ? location.getLatitude() : userCityEntity.getLat(), userCityEntity == null ? location.getLongitude() : userCityEntity.getLon());
            clearOverlay();
            updateData();
//            getUseableStation();
//            getMainCarList(carListReqBean);
//            updateData(userCityEntity == null ? location.getLongitude() : userCityEntity.getLon(), userCityEntity == null ? location.getLatitude() : userCityEntity.getLat(), userCityEntity == null ? location.getCityCode() : userCityEntity.getCityCode());
        }
    }

    @OnClick({R.id.main_todo_iv, R.id.main_city_name_layout, R.id.main_car_list_btn, R.id.main_search_btn, R.id.main_function_refresh
            , R.id.main_function_location, R.id.main_bottom_btn_reporting, R.id.main_bottom_btn_nav, R.id.main_bottom_btn_control,
            R.id.main_select_condition_btn, R.id.main_order_detail_btn, R.id.main_car_state_layout})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_todo_iv://待办列表
                Intent todo_intent = new Intent(NormalHomeActivity.this, ToDoCarListActivity.class);
                NormalHomeActivity.this.startActivity(todo_intent);
                break;
            case R.id.main_car_list_btn://车辆列表
                Intent intent = new Intent(NormalHomeActivity.this, CarListActivity.class);
                Bundle bundle = new Bundle();
                if (userCityEntity != null) {
                    bundle.putParcelable(Constants.BUNDLE_DATA, userCityEntity);
                }
                if (carListReqBean != null) {
                    bundle.putParcelable(Constants.BUNDLE_DATA_EXT, carListReqBean);
                }
                if (!bundle.isEmpty()) {
                    intent.putExtras(bundle);
                }
                NormalHomeActivity.this.startActivity(intent);

                break;
            case R.id.main_search_btn://查找
                Intent searchIntent = new Intent(NormalHomeActivity.this, SearchCarActivity.class);
                startActivity(searchIntent);
                break;
            case R.id.main_city_name_layout:
//                Intent intentCity = new Intent(this, CityListActivity.class);
//                startActivityForResult(intentCity, ReqConstants.REQUEST_CODE_FOR_SELECT_CITY);
                break;
            case R.id.main_select_condition_btn:
                Intent intentCondition = new Intent(this, SelectConditionActivity.class);
                Bundle bundleCondition = new Bundle();
                bundleCondition.putParcelable(Constants.BUNDLE_DATA, carListReqBean);
                intentCondition.putExtras(bundleCondition);
                startActivityForResult(intentCondition, ReqConstants.REQUEST_CODE_FOR_SELECT_CONDITION);
                break;
            case R.id.main_function_location:
                BDLocation curLocation = getCurValidAndCityLocation();
                // 定位当前位置，如果当前位置有效的话地图移动到我的定位
                if (curLocation != null) {
                    changePosition(curLocation.getLatitude(), curLocation.getLongitude());
                    // 判断是否是当前定位的城市，如果定位城市和选择的城市不一样的话，会进行数据刷新以及更新城市等操作
                    /*if (!isLocationCity(curLocation, userCityEntity)) {
                        userCityEntity = null;//切回定位城市，清除内存usercity
//                        Constants.userCityCode = "";
                        mainViewHelper.updateCityName(curLocation.getCity());
                        updateData(curLocation.getLongitude(), curLocation.getLatitude(), curLocation.getCityCode());
                    }*/
                }
                break;
            case R.id.main_function_refresh:
                doRefreshMap();
                break;

            case R.id.main_bottom_btn_reporting:
            case R.id.main_car_state_layout:
                Intent history_intent = new Intent(NormalHomeActivity.this, HistoryCarListActivity.class);
                history_intent.putExtra(Constants.BUNDLE_DATA, carDetailEntity.getCarId());
                history_intent.putExtra(Constants.BUNDLE_DATA_EXT, carDetailEntity.getCarNum());
                NormalHomeActivity.this.startActivity(history_intent);
                break;
            case R.id.main_bottom_btn_nav:
                NavigationUtils.showNavigationDialog(NormalHomeActivity.this, new LatLng(curSelCarEntity.getLat(), curSelCarEntity.getLng()),
                        NavigationUtils.Driving, NavigationUtils.ReturnCar, "车辆位置");
                break;
            case R.id.main_bottom_btn_control:
                Intent controlIntent = new Intent(NormalHomeActivity.this, StartDealActivity.class);
                controlIntent.putExtra(Constants.BUNDLE_DATA, curSelCarEntity.getCarId());
                startActivity(controlIntent);
                break;
            case R.id.main_order_detail_btn:
                Intent curIntent = new Intent(NormalHomeActivity.this, CarDetailActivity.class);
                startActivity(curIntent);
                break;
            default:
                break;
        }
    }

    /**
     * 进行刷新地图数据
     */

    private synchronized void doRefreshMap() {
//        startLocationUpdate();//刷新定位
        DFApp.locationService.start();
        BDLocation refreshLocation = getCurValidAndCityLocation();
        getLruBitmapDescriptorCache().clearMemory();

        if (refreshLocation != null) {
            carListReqBean = new CarListReqBean();

            // 清空数据
            curSelCarEntity = null;
            // 隐藏选车按钮
            mainViewHelper.hidenSelCarView();
            clearClickInfo();
            clearOverlay();

//            String cityCode = userCityEntity == null ? refreshLocation.getCityCode() : userCityEntity.getCityCode();
//            updateData(refreshLocation.getLongitude(), refreshLocation.getLatitude(), cityCode);
            updateData();
//            getUseableStation();
            getCurrentOrderForInit();
        }
    }

    /**
     * 刷新不更新数据
     */
    private void doRefreshMapNoReqData() {
        BDLocation refreshLocation = getCurValidAndCityLocation();

        if (refreshLocation != null) {
            // 清空数据
            curSelCarEntity = null;
            // 隐藏选车按钮
            mainViewHelper.hidenSelCarView();
            clearClickInfo();

            clearOverlay();
            handlerOverlayList();

        }
    }

    /**
     *
     */
    private void clearClickInfo() {
        if (curSelCarEntity != null) {
            curSelCarEntity.setSelect(false);
        }
//        if (lastWalkingRouteOverlay != null) {
//            lastWalkingRouteOverlay.removeFromMap();
//        }
        curSelCarEntity = null;
        lastClickMarker = null;
//        curSelReturnParkingEntity = null;

    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {

        if (lastClickMarker == marker || marker.getExtraInfo() == null) {
            return false;
        }
        Bundle bundle = marker.getExtraInfo();
        if (bundle.containsKey(Constants.BUNDLE_CARENTITY)) {

            Marker changeMarker = updateParkingMarker(marker);
            lastClickMarker = changeMarker;
            CarInfo bundleItem = changeMarker.getExtraInfo().getParcelable(Constants.BUNDLE_CARENTITY);

            CarInfo originItem = getOriginParkingEntity(bundleItem.getCarId());

            curSelCarEntity = originItem;

            getCarDetailInfo(curSelCarEntity.getCarId(), location.getLatitude(), location.getLongitude());

        }

        return true;
    }

    /**
     * 更新停车场的状态
     *
     * @param marker
     * @return
     */
    private Marker updateParkingMarker(Marker marker) {
        // 如果上次点中的marker存在，则修改上次点中的marker状态。
        if (null != lastClickMarker) {
            lastClickMarker.remove();
            CarInfo lastClickCarInfo = lastClickMarker.getExtraInfo().getParcelable(Constants.BUNDLE_CARENTITY);
            lastClickCarInfo.setSelect(false);
            markerHelper.createCarMarker(lastClickCarInfo);
        }

        // 更改当前点中的marker状态
        CarInfo curItem = marker.getExtraInfo().getParcelable(Constants.BUNDLE_CARENTITY);
        marker.remove();
        curItem.setSelect(true);

        Marker changeMarker = (Marker) markerHelper.createCarMarker(curItem);
        return changeMarker;
    }

    /**
     * 更新当前路径规划
     *
     * @param curClickParkingEntity
     */
    /*private void updateRoute(ParkingEntity curClickParkingEntity) {
        // 设置路径规划
        if (null != lastWalkingRouteOverlay) {
            lastWalkingRouteOverlay.removeFromMap();
        }

        AMapLocation curLocation = getCurValidLocation();
        LatLng location_latLng = new LatLng(curLocation.getLatitude(), curLocation.getLongitude());
        LatLng parking_latLng = new LatLng(curClickParkingEntity.getParkingLat(), curClickParkingEntity.getParkingLon());
        if (isLocationCity(curLocation, userCityEntity)) {
            setRouteSearch(location_latLng, parking_latLng);
        }
    }*/

    /**
     * 请求订单状态
     */
    public void getCurrentOrderForInit() {
        RequestOptService.getUnfinishDeal(this, new Response.Listener<NetBeanWrapper<UnFinishDealRespBean>>() {
                    @Override
                    public void onResponse(NetBeanWrapper<UnFinishDealRespBean> response) {
                        if (handleBeanResponse(response)) {
                            return;
                        }

                        UnFinishDealRespBean respBean = response.getModelData();

                        if (respBean.getHasDeal() == Constants.NormalStatus.SHOW) {
                            mainViewHelper.showOrderTipLayout();
                        } else {
                            mainViewHelper.hidenOrderTipLayout();
                        }
                    }
                },
                getDefaultErrorListener());
    }


    /**
     * 封装请求数据
     */
    private void updateData() {

        if (userCityEntity != null) {
            carListReqBean.setCityCode(userCityEntity.getCityCode());
            carListReqBean.setLat(String.valueOf(userCityEntity.getLat()));
            carListReqBean.setLng(String.valueOf(userCityEntity.getLon()));
        } else {
            carListReqBean.setCityCode(location.getCityCode());
            carListReqBean.setLat(String.valueOf(location.getLatitude()));
            carListReqBean.setLng(String.valueOf(location.getLongitude()));
        }
        getMainCarList(carListReqBean);
    }

    /**
     * 获取可用站点区域
     */
    private void getUseableStation(){
        /*String backArea = "117.119905,39.088908;117.120882,39.089378;117.121525,39.088404;117.120871,39.088038;117.120672,39.088346;117.120372,39.088325;117.120308,39.088596";
        String backAreaTmp[] = backArea.split(";");

        List<LatLng> latLngList = new ArrayList<>();
        for (int j = 0; j < backAreaTmp.length; j++) {
            LatLng latLng = new LatLng(Double.parseDouble(backAreaTmp[j].substring(backAreaTmp[j].indexOf(",") + 1)),
                    Double.parseDouble(backAreaTmp[j].substring(0,backAreaTmp[j].indexOf(","))));
            latLngList.add(latLng);
        }
        //绘制多边形电子围栏
        MapOverlayHelper.addPloyOverlay(mBaiduMap, latLngList,
                AndroidUtils.getColor(this, R.color.nD90DB95F),
                new Stroke(MapOverlayHelper.DEFAULT_STROKE_WIDTH,
                        AndroidUtils.getColor(this, R.color.n0db95f)));*/

        RequestOptService.getUseableStation(this, new Response.Listener<NetBeanWrapper<UseableStationRespBean>>() {
            @Override
            public void onResponse(NetBeanWrapper<UseableStationRespBean> response) {
                if (handleBeanResponse(response)) {
                    return;
                }
                useableStationRespBean = response.getModelData();
                drawPloyOverlay(useableStationRespBean);
            }
        },getDefaultErrorListener());

    }
    /**
     * 绘制电子围栏
     */
    private void drawPloyOverlay(UseableStationRespBean useableStationRespBean) {
        if (!CheckLogicUtil.isEmpty(useableStationRespBean.getStationList())) {
                for(int i = 0;i < useableStationRespBean.getStationList().size(); i++){
                    if(useableStationRespBean.getStationList().get(i).getAreaShape() == Constants.AreaShape.CIRCLE){
                        String backArea = useableStationRespBean.getStationList().get(i).getBackArea();
                        String backAreaTmp[] = backArea.split(";");
                        //半径 四舍五入
                        BigDecimal bd = new BigDecimal(Double.parseDouble(backAreaTmp[1].toString())).setScale(0, BigDecimal.ROUND_HALF_UP);
                        int radius = Integer.parseInt(bd.toString());

                        LatLng latLng = new LatLng(Double.parseDouble(backArea.substring(backArea.indexOf(",") + 1,backArea.indexOf(";"))),
                                Double.parseDouble(backArea.substring(0,backArea.indexOf(","))));
                        MapOverlayHelper.addCircleOverlay(mBaiduMap,latLng,AndroidUtils.getColor(this, R.color.nD9ef622b),radius,
                            new Stroke(MapOverlayHelper.DEFAULT_STROKE_WIDTH,AndroidUtils.getColor(this, R.color.nef622b)));
                    }else {
                        String backArea = useableStationRespBean.getStationList().get(i).getBackArea();
                        String backAreaTmp[] = backArea.split(";");

                        List<LatLng> latLngList = new ArrayList<>();
                        for (int j = 0; j < backAreaTmp.length; j++) {
                            LatLng latLng = new LatLng(Double.parseDouble(backAreaTmp[j].substring(backAreaTmp[j].indexOf(",") + 1)),
                                    Double.parseDouble(backAreaTmp[j].substring(0,backAreaTmp[j].indexOf(","))));
                            latLngList.add(latLng);
                        }
                        //绘制多边形电子围栏
                        MapOverlayHelper.addPloyOverlay(mBaiduMap, latLngList,
                                AndroidUtils.getColor(this, R.color.nD9ef622b),
                                new Stroke(MapOverlayHelper.DEFAULT_STROKE_WIDTH,
                                        AndroidUtils.getColor(this, R.color.nef622b)));
                    }
                }
        }
    }


    private void getMainCarList(final CarListReqBean reqBean) {
//        DialogUtil.showIndeterminateProgress(getProgressDialog());
        RequestOptService.getMainCarList(this, reqBean, new Response.Listener<NetBeanWrapper<CarListRespBean>>() {
            @Override
            public void onResponse(NetBeanWrapper<CarListRespBean> response) {
//                DialogUtil.hideIndeterminateProgress(getProgressDialog());
                if (handleBeanResponse(response)) {
                    return;
                }

                carListRespBean = response.getModelData();

                updateCount(carListRespBean);
                if (CheckLogicUtil.isEmpty(carListRespBean.getCarList())
                        || carListRespBean.getCarList().size() <= 0) {
                    return;
                }
                handlerOverlayList();

            }
        }, getDefaultErrorListener());

    }

    private void updateCount(CarListRespBean carListRespBean) {
        mainViewHelper.updateCarCount(carListRespBean.getCount() + "台");
        mainViewHelper.updateCityCarTotalCount("(" + carListRespBean.getTotalCount() + ")");
    }

    private void getCarDetailInfo(int carId, double lat, double lng) {
        RequestOptService.getCarDetailInfo(this, carId, lat, lng, new Response.Listener<NetBeanWrapper<CarDetailRespBean>>() {
            @Override
            public void onResponse(NetBeanWrapper<CarDetailRespBean> response) {
                if (handleBeanResponse(response)) {
                    return;
                }
                carDetailRespBean = response.getModelData();
                carDetailEntity = carDetailRespBean.getCarVo();
                LatLng latLng = new LatLng(carDetailEntity.getLatitude(), carDetailEntity.getLongitude());
                ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption().location(latLng);
                geoCoder.reverseGeoCode(reverseGeoCodeOption);
                updateCarDetailView(carDetailEntity);
            }
        }, getDefaultErrorListener());
    }

    /**
     * 更新车辆详情view
     *
     * @param carDetailEntity
     */
    private void updateCarDetailView(CarDetailEntity carDetailEntity) {
        if (carDetailEntity != null) {
            mainViewHelper.showSelCarView();
            mainViewHelper.updateCarPlateNum(carDetailEntity.getCarNum());
            mainViewHelper.updateCarBrand(carDetailEntity.getBrand());
            mainViewHelper.updateCarState(carDetailEntity.getStatusDesc());
            mainViewHelper.updateCarMileage(carDetailEntity.getRemainMileageDesc());
            mainViewHelper.updateCarBattery(carDetailEntity.getPowerDesc());
            mainViewHelper.updateCarCharingState(carDetailEntity.getChargeStatusDesc());
            mainViewHelper.updateMachineState(carDetailEntity.getOnlineStatusDesc());
            mainViewHelper.updateDistance(carDetailEntity.getDistanceDesc());
            if (carDetailEntity.getLastDeal() != null) {
                /*if (!CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getEndTime())) {
                    mainViewHelper.updateCarStateDescTime(carDetailEntity.getLastDeal().getEndTime(),R.color.black);
                } else {
                    mainViewHelper.updateCarStateDescTime(getString(R.string.manage_doing_txt),R.color.nf26050);
                }*/
                mainViewHelper.updateCarStateDescTime(carDetailEntity.getLastDeal().getStartTime());
                mainViewHelper.updateOperation(carDetailEntity.getLastDeal().getAdminName());
                if (!CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getCause()) && !CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getDetail())) {
                    mainViewHelper.updateCarStateDesc(carDetailEntity.getLastDeal().getCause() + "," + carDetailEntity.getLastDeal().getDetail());
                } else if (!CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getDetail())) {
                    mainViewHelper.updateCarStateDesc(carDetailEntity.getLastDeal().getDetail());
                } else if (!CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getCause())) {
                    mainViewHelper.updateCarStateDesc(carDetailEntity.getLastDeal().getCause());
                } else if (CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getCause()) && CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getDetail())) {
                    mainViewHelper.updateCarStateDesc("");
                }
            } else {
                mainViewHelper.updateCarStateDescTime(Constants.BLANK);
                mainViewHelper.updateCarStateDesc(Constants.BLANK);
                mainViewHelper.updateOperation(Constants.BLANK);
            }
        }
    }

    /**
     * 处理数据
     */
    private void handlerOverlayList() {
        clearOverlay();
        setOpenUserLocation(true);
        addOverlayList(carListRespBean);
    }

    /**
     * 增加overlay 地图覆盖物
     */
//    private void updateOverlayView(OverLayEntity overlayInfo) {
//
//        mainViewHelper.hidenSelCarLlyt();
//        mainViewHelper.showRecommendView();
//
//    }

    /**
     * 增加overlay 地图覆盖物
     *
     * @param overLayEntityList
     */
//    private float getParkingZoom(List<OverLayEntity> overLayEntityList) {
//        if (CheckLogicUtil.isEmpty(overLayEntityList)) {
//            return MAP_ZOOM_DEFAULT;
//        }
//
//        for (OverLayEntity item : overLayEntityList) {
//            if (item.type == Constants.PARKING_MARKER_TYPE.PARKING_MARKER) {
//                return item.min + 1;
//            }
//        }
//        return MAP_ZOOM_DEFAULT;
//    }

    /**
     * 从网点实体取得当前parkingID对应的实体
     *
     * @param overLayEntityList
     * @param parkingID
     * @return
     */
//    private CarInfo getParkingEntityOverlay(List<OverLayEntity> overLayEntityList, String parkingID) {
//        if (CheckLogicUtil.isEmpty(overLayEntityList)) {
//            return null;
//        }
//
//        for (OverLayEntity item : overLayEntityList) {
//            if (item.type == Constants.PARKING_MARKER_TYPE.PARKING_MARKER) {
//                return getParkingEntity(item.parkingList, parkingID);
//            }
//        }
//        return null;
//    }

    /**
     * 获取原始的网点对象 由于parcel不是引用的对象，实际上相当于克隆，所以容易造成不同步的问题
     *
     * @return
     */
    private CarInfo getOriginParkingEntity(int carId) {
        if (carListRespBean != null && !CheckLogicUtil.isEmpty(carListRespBean.getCarList())) {
            CarInfo item = getParkingEntity(carListRespBean.getCarList(), carId);
            return item;
        }
        return null;
    }

    /**
     * 更新网点的数据
     *
     * @param carId
     * @param select
     */
    private void updateOriginParkingEntity(int carId, boolean select) {
        CarInfo item = getOriginParkingEntity(carId);
        if (item != null) {
            item.setSelect(select);
        }
    }

    /**
     * 从网点实体取得当前parkingID对应的实体
     *
     * @param carInfoList
     * @param carId
     * @return
     */
    private CarInfo getParkingEntity(List<CarInfo> carInfoList, int carId) {
        if (CheckLogicUtil.isEmpty(carInfoList)) {
            return null;
        }
        for (CarInfo carInfo : carInfoList) {
            if (carInfo.getCarId() == carId) {
                return carInfo;
            }
        }

        return null;
    }

    /**
     * 增加overlay到地图上
     */
    private void addOverlayList(CarListRespBean carListRespBean) {

        if (carListRespBean == null) {
            return;
        }

        BaiduRunnable addOverlayRunnable;

        addOverlayRunnable = new CarOverlayRunnable(mainViewHelper, getBaiduMap(), carListRespBean.getCarList(), markerHelper, new BaiduRunnable.MyRunnableListener() {
            @Override
            public void handleFinish(List<Overlay> dataList) {

                if (!CheckLogicUtil.isEmpty(dataList)) {
                    //  对于已经被选中的view 设置最后被点击的view
                    for (Overlay item : dataList) {
                        if (item.getExtraInfo().getBoolean(Constants.BUNDLE_DATA, false)) {
                            lastClickMarker = (Marker) item;
                        }
                    }
                }
            }
        });

        getThreadHandler().post(addOverlayRunnable);

        getUseableStation();

    }


    /**
     * 用户选择的城市是否为定位城市
     *
     * @return
     */
    private boolean isLocationCity(BDLocation location, CityEntity cityEntity) {
        if (cityEntity == null || location == null) {
            return true;
        }
        return cityEntity.cityCode.equals(location.getCityCode());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            if (ReqConstants.REQUEST_CODE_FOR_SELECT_CITY == requestCode) {
                //选择城市
                userCityEntity = data.getParcelableExtra(Constants.Tag.CITY_ENTITY);
                if (userCityEntity == null) {
                    mainViewHelper.updateCityName(null);
                } else {
//                    Constants.userCityCode = userCityEntity.getCityCode();
                    mainViewHelper.updateCityName(userCityEntity.getName());

//                    BDLocation bdLocation = getCurValidLocation();

//                    if (bdLocation == null) {
//                        return;
//                    }
                    clearClickInfo();

                    changePosition(userCityEntity.getLat(), userCityEntity.getLon());
                    clearOverlay();
                    carListReqBean = new CarListReqBean();
                    updateData();
//                    getUseableStation();
//                    getMainCarList(carListReqBean);
//                    updateData(userCityEntity.getLon(), userCityEntity.getLat(), userCityEntity.getCityCode());
                }
            } else if (ReqConstants.REQUEST_CODE_FOR_SELECT_CONDITION == requestCode) {
                clearOverlay();
                mainViewHelper.hidenSelCarView();
                carListReqBean = new CarListReqBean();
                carListReqBean = data.getParcelableExtra(Constants.Tag.SELECT_CONDITION);

//                getMainCarList(carListReqBean);
                updateData();
            }
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        // 设置当前的网点作为选中网点
        mainViewHelper.hidenSelCarView();

        if (curSelCarEntity != null) {

            if (lastClickMarker != null) {
                lastClickMarker.remove();
            }

            curSelCarEntity.setSelect(false);
            markerHelper.createCarMarker(curSelCarEntity);
        }
        curSelCarEntity = null;
        lastClickMarker = null;
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    public void onBackPressed() {

        DialogUtil.creatBaseNoTitleDialog(NormalHomeActivity.this, "是否退出" + getResources().getString(R.string.app_name), "确定", "取消")
                .getBuilder()
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        SkipUtil.exitAPP(NormalHomeActivity.this);
                    }
                })
                .show();
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有检索到结果
        }
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有检索到结果
        } else {
            mainViewHelper.updateCarAddress(reverseGeoCodeResult.getAddress());
        }
    }

    /**
     * 定时刷新的runnable
     */
    /*private class TimeIntervalRefreshRunnable implements Runnable {

        @Override
        public void run() {
            doRefreshMap();
            getUiHandler().postDelayed(this, TIME_INTERVAL_REFRESH);
        }
    }*/

    /**
     * 获取当前点击的mark 距离地图上部 指定位置的距离， 如果为正值 则说明在上边，如果为负值 则说明点击的点在下部会被现实的选车view遮挡
     *
     * @param curMarkLatLng
     * @return
     */
    /*private double getCurLatitudeOffset(LatLng curMarkLatLng) {
        LatLngBounds bound = getBaiduMap().getMapStatus().bound;
        return (bound.northeast.latitude - bound.southwest.latitude) * 7 / 10 + bound.southwest.latitude - curMarkLatLng.latitude;
    }*/

    /**
     * 切换屏幕重点点 纬度进行偏移
     *
     * @param markerLatitudeOffset 偏移距离
     */
    /*private void moveCenterLatitudeOffset(double markerLatitudeOffset, double originLongitude) {
        LatLng centerLatLng = getBaiduMap().getMapStatus().target;
        double centerLatitudeOffset = centerLatLng.latitude - markerLatitudeOffset;
        changePosition(centerLatitudeOffset, originLongitude);
    }*/


}
